//
//  MMGReleaseInformationViewController.swift
//  MyMicroblog
//
//  Created by Mac on 17/1/12.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

// 注册工具栏按钮 tag 值
enum BottomToolButtonTag: Int {
    case Picture = 100
    case AtSomeone
    case NumberSign
    case Face
    case Add
}
private let baseTag = 100

class MMGReleaseInformationViewController: MMGBaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置顶部导航栏
        setNavigationBar()
        // 设置页面
        setupViews()
        // 设置底部工具栏
        setBottomToolBar()
        // 注册通知
        registerNotification()
    }
    
    // MARK:设置页面
    private func setupViews() {
        // 设置输入框
        view.addSubview(inputTextView!)
        // 添加占位文本
        inputTextView?.addSubview(placeHolder)
        
        // 设置约束
        inputTextView?.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.height.equalTo(ScreenHeight / 3)
        }
        placeHolder.snp.makeConstraints { (make) in
            make.left.equalTo(inputTextView!).offset(5)
            make.top.equalTo(inputTextView!).offset(8)
        }
    }
    
    // MARK:发布消息
    @objc private func releaseInformation(){
        // 设置请求地址
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        // 设置参数
        let parameter = ["access_token" : MMGUserAccountViewModel.shared.access_token,
                         "status" : inputTextView?.text,]
        // 访问网络,将微博推送到服务器
        if self.pictureSelectorController.selectorImages.count != 0 {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let pictureData = UIImagePNGRepresentation(self.pictureSelectorController.selectorImages.first!)
            MMGNetworkTool.shared.post(urlString, parameters: parameter, constructingBodyWith: { (formData) in
                formData.appendPart(withFileData: pictureData!, name: "pic", fileName: "xxxxxxx", mimeType: "application/octet-stream")
            }, progress: { (progress) in
                print(progress)
            }, success: { (_, result) in
                SVProgressHUD.showSuccess(withStatus: "发送成功,快去看看大作吧")
                self.closeController()
            }, failure: { (_, result) in
                SVProgressHUD.showError(withStatus: "发送失败,请检查网络状态")
            })
        }else{
            
            MMGNetworkTool.shared.request(Method: .MethodPost, urlString: urlString, parameters: parameter) { (objc, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败,请检查网络状态")
                }else{
                    SVProgressHUD.showSuccess(withStatus: "发送成功,快去看看大作吧")
                    self.closeController()
                }
            }
        }
    }
    
    // MARK:工具栏按钮点击事件
    @objc private func clickToolButton(button: UIButton) {
        
        let tagValue = BottomToolButtonTag.init(rawValue: button.tag)!
        switch tagValue {
        case .Picture:
            addPicture()
        case .AtSomeone:
            atSomebody()
        case .NumberSign:
            showNumberKeyBoard()
        case .Face:
            showFacingBag()
        case .Add:
            addMoreFunc()
        }
    }
    
    // MARK:监听键盘位置变化
    @objc private func keyBoardChanged(noti: Notification) {
        // 获取结束的键盘位置信息
        let endFrame = noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        // 获取 Y 轴偏移量
        let offSetY = -(ScreenHeight - endFrame.minY)
        // 更新约束
        bottomToolBar?.snp.updateConstraints({ (make) in
            make.bottom.equalTo(view).offset(offSetY)
        })
        // 强制刷新
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK:设置导航栏
    private func setNavigationBar() {
        // 添加右端发布 item
        navigationItem.rightBarButtonItem = UIBarButtonItem(backImage: #imageLiteral(resourceName: "common_button_orange"), backImageHighLighted: #imageLiteral(resourceName: "common_button_orange_highlighted"), backImageDisable: #imageLiteral(resourceName: "common_button_white_disable"), size: CGSize.init(width: 80, height: 35), title: "发布", fontSize: 17,target: self, action: #selector(releaseInformation))
        navigationItem.rightBarButtonItem?.isEnabled = false
        // 修改左端关闭编辑按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeController))
        // 修改背景色
        navigationController?.navigationBar.subviews.first?.subviews.last?.backgroundColor = UIColor.red
        // 设置 titleLabel
        let titleLab = UILabel()
        titleLab.textAlignment = .center
        titleLab.numberOfLines = 0
        
        if let userName = MMGUserAccountViewModel.shared.userAccountDTO?.name {
            let titleText = "发布微博\n\(userName)"
            titleLab.text = titleText
            // 修改属性文本的属性为可变属性
            let strM = NSMutableAttributedString(string: titleText)
            // 获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            // 依据范围为用户名添加属性
            strM.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName : UIColor.orange], range: range)
            // 修改 titleLab 文本属性
            titleLab.attributedText = strM
        }else{
            titleLab.text = "发布微博"
        }
        titleLab.sizeToFit()
        navigationItem.titleView = titleLab
    }
    
    // MARK:设置底部控制块
    private func setBottomToolBar() {
        // 添加底部工具栏
        view.addSubview(bottomToolBar!)
        // 准备工具按钮,获取背景图片名称
        let imageNames: [String] = [ "compose_toolbar_picture",
                                     "compose_mentionbutton_background",
                                     "compose_trendbutton_background",
                                     "compose_emoticonbutton_background",
                                     "compose_add_background"]
        // 遍历图片名称数组, 创建工具按钮,加入到管理空间中
        var index: Int = 0
        for imageName in imageNames {
            let imageNameHigh = "\(imageName)_highlighted"
            let button = UIButton(imageNameNormal: imageName, imageNameHight: imageNameHigh)
            button.tag = baseTag + index
            button.backgroundColor = UIColor(white: 0.9, alpha: 1)
            button.addTarget(self, action: #selector(clickToolButton(button:)), for: .touchUpInside)
            bottomToolBar?.addArrangedSubview(button)
            index += 1
        }
        // 设置约束
        bottomToolBar?.snp.makeConstraints({ (make) in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        })
    }
    
    // MARK:懒加载编辑输入框
    lazy var inputTextView: UITextView? = {
        // 创建 textView
        let textView = UITextView(frame: CGRect.zero)
        textView.backgroundColor = UIColor(white: 0.9, alpha: 1)
        textView.delegate = self
        textView.font = UIFont.systemFont(ofSize: 17)
        textView.textColor = UIColor.darkGray
        textView.keyboardDismissMode = .onDrag
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    // MARK:设置占位文本
    var placeHolder = UILabel(text: "请输入您想要告诉粉丝们的话", textColor: UIColor.lightGray, textFontSize: 17)
    
    
    // MARK:懒加载底部工具栏
    lazy var bottomToolBar: UIStackView? = {
        let tool = UIStackView(frame: CGRect.zero)
        tool.distribution = .fillEqually
        tool.axis = .horizontal
        return tool
    }()
    
    // MARK:懒加载图片选择控制器
    lazy var pictureSelectorController: MMGPictureSelectorViewController = {
        
        let selCtr = MMGPictureSelectorViewController(collectionViewLayout: UICollectionViewFlowLayout())
        
        return selCtr
    }()
    
    // MARK:关闭页面
    func closeController() {
        UIView.animate(withDuration: 0.25) {
            self.view.alpha = 0
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    // MARK:注册通知,监听键盘状态的变化
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardChanged(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    // MARK:移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK:
// MARK: 分类中实现textView代理方法
extension MMGReleaseInformationViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        // 这种方式判断的并不精确
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        placeHolder.isHidden = textView.hasText
    }
}

// MARK:
// MARK: 分类中实现工具栏按钮点击事件
extension MMGReleaseInformationViewController {
    
    // MARK: 添加图片按钮点击事件
    func addPicture() {
        // 将选择控制器加载到当前控制器中
        self.addChildViewController(pictureSelectorController)
        self.view.insertSubview(pictureSelectorController.view, belowSubview: self.bottomToolBar!)
        pictureSelectorController.view.snp.makeConstraints { (make) in
            make.top.equalTo((self.inputTextView?.snp.bottom)!).offset(10)
            make.left.equalTo(self.view).offset(5)
            make.right.equalTo(self.view).offset(-5)
            make.bottom.equalTo((self.bottomToolBar?.snp.top)!)
        }
    }
    //MARK: @某些人
    func atSomebody() {
    
    }
    // MARK: 显示数字键盘
    func showNumberKeyBoard() {
    
    }
    // MARK: 显示表情包
    func showFacingBag() {
    
    }
    // MARK: 显示更多
    func addMoreFunc() {
    
    }
}
